package com.sk.weichat.ui.mucfile;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sk.weichat.R;
import com.sk.weichat.bean.EmptyData;
import com.sk.weichat.ui.base.LazyFragment;
import com.sk.weichat.ui.mucfile.adapter.DividerAdapter;
import com.sk.weichat.ui.mucfile.adapter.EmptyAdapter;
import com.sk.weichat.ui.mucfile.adapter.FileAdapter;
import com.sk.weichat.ui.mucfile.adapter.TypeAdapter;
import com.sk.weichat.ui.mucfile.bean.FileBean;
import com.sk.weichat.util.MediaHelper;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static com.sk.weichat.ui.mucfile.AddMucFileActivity2.Action_Click;

public class MediaVideoAndAudioFragment2 extends LazyFragment implements MediaHelper.OnQueryListener {
    SmartRefreshLayout refreshLayout;

    EmptyData emptyData = new EmptyData("该分类暂无内容");

    private LinkedList<DelegateAdapter.Adapter> adapterList = new LinkedList<>();
    private DelegateAdapter delegateAdapter;

    private TypeAdapter videoTypeAdapter;
    private TypeAdapter audioTypeAdapter;
    private FileAdapter videoAdapter;
    private FileAdapter audioAdapter;
    private List<FileBean> videoBeans = new ArrayList<>();
    private List<FileBean> audioBeans = new ArrayList<>();

    //记录展开的项
    Map<String, Boolean> expandMap = new HashMap<>();
    //记录选择的Item
    Map<String, Boolean> checkedMap = new HashMap<>();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    protected int getLayoutRes() {
        return R.layout.fragment_media_video_and_audio;
    }

    @Override
    protected void loadData() {
        //扫描文件时间过长，缓存不为空，显示缓存
        if (MediaHelper.getInstance().getAudioQueryCache() != null) {
            onDataSuccess(MediaHelper.getInstance().getAudioQueryCache());
        } else {
            refreshLayout.autoRefresh();
        }
        if (MediaHelper.getInstance().getVideoQueryCache() != null) {
            onDataSuccess(MediaHelper.getInstance().getVideoQueryCache());
        }

    }

    @Override
    protected void initView(View view) {
        refreshLayout = view.findViewById(R.id.refresh_layout);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                realLoadData();
            }
        });
        VirtualLayoutManager layoutManager = new VirtualLayoutManager(getActivity());

        RecyclerView recyclerView = view.findViewById(R.id.recyclerview);
        recyclerView.setLayoutManager(layoutManager);
        delegateAdapter = new DelegateAdapter(layoutManager, false);

        recyclerView.setAdapter(delegateAdapter);
        initAdapter();
    }

    private void initAdapter() {
        videoAdapter = new FileAdapter(mContext, new ArrayList<>());
        videoAdapter.setOnFileBeanClickListener(new FileAdapter.OnFileBeanClickListener() {
            @Override
            public void onClick(FileBean fileBean, int pos) {
                selectItem(fileBean);
                videoAdapter.notifyItemChanged(pos);
            }
        });
        audioAdapter = new FileAdapter(mContext, new ArrayList<>());
        audioAdapter.setOnFileBeanClickListener(new FileAdapter.OnFileBeanClickListener() {
            @Override
            public void onClick(FileBean fileBean, int pos) {
                selectItem(fileBean);
                audioAdapter.notifyItemChanged(pos);
            }
        });
        List<FileBean> list = new ArrayList<>();
        FileBean fileBean = new FileBean();
        fileBean.setType(FileBean.DIR);
        fileBean.setTypeName("音频");
        list.add(fileBean);
        audioTypeAdapter = new TypeAdapter(mContext, list);
        audioTypeAdapter.setOnTypeClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FileBean typeBean = audioTypeAdapter.getData().get(0);
                if (typeBean.isExpand()) {
                    //折叠
                    typeBean.setExpand(false);
                    expandMap.put(typeBean.getTypeName(), false);
                    audioAdapter.getData().clear();
                    audioAdapter.notifyItemRangeRemoved(0, audioBeans.size());
                } else {
                    //展开
                    try {
                        typeBean.setExpand(true);
                        expandMap.put(typeBean.getTypeName(), true);
                        audioAdapter.getData().addAll(audioBeans);
                        audioAdapter.notifyItemRangeInserted(0, audioBeans.size());
                    } catch (Exception e) {

                    }
                }
                audioTypeAdapter.notifyItemChanged(0);
            }
        });


        List<FileBean> list2 = new ArrayList<>();
        FileBean fileBean2 = new FileBean();
        fileBean2.setType(FileBean.DIR);
        fileBean2.setTypeName("视频");
        list2.add(fileBean2);
        videoTypeAdapter = new TypeAdapter(mContext, list2);
        videoTypeAdapter.setOnTypeClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FileBean typeBean = videoTypeAdapter.getData().get(0);
                if (typeBean.isExpand()) {
                    //折叠
                    typeBean.setExpand(false);
                    expandMap.put(typeBean.getTypeName(), false);
                    videoAdapter.getData().clear();
                    videoAdapter.notifyItemRangeRemoved(0, videoBeans.size());
                } else {
                    //展开
                    typeBean.setExpand(true);
                    expandMap.put(typeBean.getTypeName(), true);
                    videoAdapter.getData().addAll(videoBeans);
                    videoAdapter.notifyItemRangeInserted(0, videoBeans.size());
                }
                videoTypeAdapter.notifyItemChanged(0);
            }
        });
    }

    private void selectItem(FileBean fileBean) {
        if (AddMucFileActivity2.isAllowToSelect() || fileBean.isChecked()) {
            fileBean.setChecked(!fileBean.isChecked());
            //发送广播
            Intent intent = new Intent();
            intent.setAction(Action_Click);
            intent.putExtra(FileBean.FileBean_Key, fileBean);
            LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
        } else {
            Toast.makeText(mContext, mContext.getString(R.string.select_file_count_place_holder, 9), Toast.LENGTH_SHORT).show();
        }
        checkedMap.put(fileBean.getFile().getAbsolutePath(), fileBean.isChecked());
    }

    private boolean once;

    private void onDataSuccess(List<File> files) {
        Observable.create(new ObservableOnSubscribe<Object>() {

            @Override
            public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
                //耗时操作
                try {
                    if (!once) {
                        //设置第一项展开
                        once = true;
                        videoTypeAdapter.getData().get(0).setExpand(true);
                        expandMap.put(videoTypeAdapter.getData().get(0).getTypeName(), true);
                    }
                    fillData(files);
                    addAapter();
                } catch (Exception e) {
                    emitter.onError(e);
                }
                emitter.onNext(new Object());
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Object>() {

                    @Override
                    public void accept(Object o) throws Exception {
                        delegateAdapter.clear();
                        delegateAdapter.setAdapters(adapterList);
                        delegateAdapter.notifyDataSetChanged();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                    }
                });
    }

    private void addAapter() {
        adapterList.clear();
        if (videoBeans.size() > 0) {
            if (expandMap.get(videoTypeAdapter.getData().get(0).getTypeName()) != null && expandMap.get(videoTypeAdapter.getData().get(0).getTypeName())) {
                videoAdapter.getData().clear();
                videoAdapter.getData().addAll(videoBeans);
            }
            adapterList.add(videoTypeAdapter);
            adapterList.add(videoAdapter);
            adapterList.add(new DividerAdapter(mContext));
        }
        if (audioBeans.size() > 0) {
            if (expandMap.get(audioTypeAdapter.getData().get(0).getTypeName()) != null && expandMap.get(audioTypeAdapter.getData().get(0).getTypeName())) {
                audioAdapter.getData().clear();
                audioAdapter.getData().addAll(audioBeans);
            }
            adapterList.add(audioTypeAdapter);
            adapterList.add(audioAdapter);
            adapterList.add(new DividerAdapter(mContext));
        }
        if (videoBeans.size() == 0 && audioBeans.size() == 0) {
            //无数据加载无数据页面
            adapterList.add(new EmptyAdapter(mContext));
        }
    }

    private void fillData(List<File> files) {

        for (int i = 0; i < files.size(); i++) {
            try {
                File file = files.get(i);
                String suffix = file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf(".") + 1, file.getAbsolutePath().length());
                FileBean fileBean = new FileBean();
                fileBean.setFile(file);
                fileBean.setChecked(checkedMap.get(file.getAbsolutePath()) != null ? checkedMap.get(file.getAbsolutePath()) : false);
                fileBean.setFileName(file.getName());
                if ((suffix.equalsIgnoreCase("mp4") || suffix.equalsIgnoreCase("avi")) && file.length() < 1024 * 1024 * 1024) {
                    //视频 小于1G
                    fileBean.setType(FileBean.MP4);
                    videoBeans.add(fileBean);
                } else if ((suffix.equalsIgnoreCase("mp3") || suffix.equalsIgnoreCase("amr")) && file.length() < 1024 * 1024 * 1024) {
                    //音频
                    fileBean.setType(FileBean.MP3);
                    audioBeans.add(fileBean);
                }
            } catch (Exception e) {

            }
        }
    }


    private void realLoadData() {
        videoBeans.clear();
        audioBeans.clear();

        //查询视频
        MediaHelper.getInstance().getMediaVideo(getActivity().getContentResolver(), this);
        //查询音频
        MediaHelper.getInstance().getMediaAudio(getActivity().getContentResolver(), this);

    }


    @Override
    public void onSuccess(List<File> files) {
        refreshLayout.finishRefresh();
        onDataSuccess(files);
    }

    @Override
    public void onFailed(String msg) {
        refreshLayout.finishRefresh();
    }
}
